<?php

/**
 * Created by PhpStorm
 * User Niu Yong Qiang
 * Date 2021/9/17 19:20
 */

namespace App\Services\Api;

use App\Enum\enum_user_message;
use App\Http\Format\FormatBase;
use App\Models\BreederUserModel;
use App\Models\CityChinaModel;
use App\Models\GoodsModel;
use App\Models\OpLogsModel;
use App\Models\OpLogsSearchModel;
use App\Models\OrderModel;
use App\Models\PetsModel;
use App\Models\SysRolePermissionsModel;
use App\Models\SysUserRoleModel;
use App\Models\TagsModel;
use App\Models\UserFriendModel;
use App\Models\UserLoginLogsModel;
use App\Models\UserMessageModel;
use App\Models\UserModel;
use App\Models\UserPublicModel;
use App\Models\UserPublicSearchModel;
use App\Models\UserSignLogsModel;
use App\Models\UserSignModel;
use App\Models\UserTokenModel;
use App\Models\WarehouseModel;
use App\Models\WarehouseUseLogsModel;
use App\Services\CommonService;
use Exception;
use Illuminate\Support\Facades\DB;

class UserService extends CommonService
{
    public function getUserCode($userData, $shareToken = ''): array
    {
        if (empty($userData['openid'])) {
            return [];
        }

        //查询用户是否存在openid
        $userOne = UserModel::getSingle(['unionid' => $userData['unionid']]);

        if (!empty($userOne)) {
            //查询token
            $md5_temp = md5($userData['openid']);
            $user_temp = UserTokenModel::getSingle(['token'=> $md5_temp]);
            if (empty($user_temp)){
                UserTokenModel::insertSingle([
                    'token' => $md5_temp,
                    'user_id' => $userOne['id'],
                    'status' => 1,
                    'created_at' => time(),
                    'expired_at' => time() + (86400 * 7),
                ]);
            }

            return [md5($userData['openid'])];
        }

        //openid，token入库，
        $data['openid'] = $userData['openid'] ?? '';
        $data['unionid'] = $userData['unionid'] ?? '';
        $data['created_at'] = time();
        $data['created_date'] = date('Ymd',time());

        $this->beginTransaction();
        try {
            //创建用户
            $userId = UserModel::insertSingle($data);
            //创建用户token记录
            UserTokenModel::insertSingle([
                'token' => md5($data['openid']),
                'user_id' => $userId,
                'status' => 1,
                'created_at' => time(),
                'expired_at' => time() + (86400 * 7),
            ]);

            //给分享人奖励
            if (!empty($shareToken)) {
                //查询分享人
                $tokenUser = UserTokenModel::getUserOne(['token' => $shareToken]);
                //发放奖励
                $this->handleAward($tokenUser['user_id'], 0, $userId, 1);

            }

            $this->commit();

            return [md5($userData['openid'])];

        } catch (Exception $e) {
            $this->rollBack();
            return [];

        }

    }

    public function getUserCodeH5($userData, $shareToken = ''): array
    {
        if (empty($userData['openid'])) {
            return [];
        }

        //查询用户是否存在openid
        $userOne = UserModel::getSingle(['unionid' => $userData['unionid']]);

        if (!empty($userOne)) {
            //查询token
            $md5_temp = md5($userData['openid'] . 'h5');
            $user_temp = UserTokenModel::getSingle(['token'=> $md5_temp]);
            if (empty($user_temp)){
                UserTokenModel::insertSingle([
                    'token' => $md5_temp,
                    'user_id' => $userOne['id'],
                    'status' => 2,
                    'created_at' => time(),
                    'expired_at' => time() + (86400 * 7),
                ]);
            }
            return [$md5_temp];
        }

        //openid，token入库，
        $data['openid'] = $userData['openid'] ?? '';
        $data['unionid'] = $userData['unionid'] ?? '';
        $data['created_at'] = time();
        $data['created_date'] = date('Ymd',time());

        $this->beginTransaction();
        try {
            //创建用户
            $userId = UserModel::insertSingle($data);
            //创建用户token记录
            UserTokenModel::insertSingle([
                'token' => md5($data['openid'] . 'h5'),
                'user_id' => $userId,
                'status' => 2,
                'created_at' => time(),
                'expired_at' => time() + (86400 * 7),
            ]);

            //给分享人奖励
            if (!empty($shareToken)) {
                //查询分享人
                $tokenUser = UserTokenModel::getUserOne(['token' => $shareToken]);
                //发放奖励
                $this->handleAward($tokenUser['user_id'], 0, $userId, 1);

            }

            $this->commit();

            return [md5($userData['openid'] . 'h5')];

        } catch (Exception $e) {
            $this->rollBack();
            return [];

        }

    }

    /**
     * 记录奖励日志
     * @param $tokenUser
     * @param $userId
     * @param $award
     * @return void
     */
    public function handleAwardLogs($tokenUser, $userId, $award)
    {
        $insert['user_id'] = $tokenUser;
        $insert['award'] = $award;
        $insert['op_id'] = $userId;
        $insert['created_at'] = time();
        UserSignLogsModel::insertSingle($insert);
    }

    /**
     * 发放奖励
     * @param $tokenUser
     * @param $userSignId
     * @param int $userId
     * @param int $style
     * @return void
     */
    public function handleAward($tokenUser, $userSignId, int $userId = 0, int $style = 0)
    {
        if (!empty($tokenUser)) {
            //查询奖励
            $award = UserSignModel::getSingle(['day' => $userSignId]);
            if (!empty($award['award'])) {
                $award = json_decode($award['award'], true);
                foreach ($award as $value) {
                    $goods = GoodsModel::getSingle(['id' => $value['goods_id']]);
                    $value['goods_name'] = $goods['goods_name'];
                    $value['weight'] = $goods['weight'];
                    $value['weight_type'] = $goods['weight_type'];
                    $value['weight_json'] = $goods['weight_json'];
                    $value['type'] = $goods['type'];

                    //把奖励加到分享人仓库 buy_num
                    $insert['user_id'] = $tokenUser;
                    $insert['goods_id'] = $value['goods_id'];
                    $insert['goods_name'] = $value['goods_name'];
                    $insert['weight'] = $value['weight'];
                    $insert['weight_type'] = $value['weight_type'];
                    $insert['weight_json'] = $value['weight_json'];
                    $insert['buy_num'] = $value['num'];
                    $insert['type'] = $value['type'];
                    $insert['created_at'] = time();
                    WarehouseModel::insertSingle($insert);
                }

                //记录奖励日志
                if (!empty($style)) {
                    $this->handleAwardLogs($tokenUser, $userId, json_encode($award));

                }
            }
        }
    }

    /**
     * 填充用户数据
     * @param array $userData
     * @return int
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function dealtUserData(array $userData): int
    {
        $data = [];
        if (!empty($userData['mobile'])) {
            $data['mobile'] = $userData['mobile'];
        }

        if (!empty($userData['nickname'])) {
            $data['nickname'] = $userData['nickname'];
        }

        if (!empty($userData['head_img_url'])) {
            $data['head_img_url'] = $userData['head_img_url'];
        }

        if (!empty($userData['sign'])) {
            $data['sign'] = $userData['sign'];
        }

        if (!empty($userData['referrer_id'])) {
            $data['referrer_id'] = $userData['referrer_id'];
        }

        if (!empty($userData['number'])) {
            $data['number'] = $userData['number'];
        }

        if (!empty($userData['area_province_id'])) {
            $data['area_province_id'] = $userData['area_province_id'];
        }

        if (!empty($userData['area_city_id'])) {
            $data['area_city_id'] = $userData['area_city_id'];
        }

        if (!empty($userData['area_district_id'])) {
            $data['area_district_id'] = $userData['area_district_id'];
        }


        if (empty($data)) {
            return 0;
        }

        return UserModel::updateSingle(['id' => adminUserInfo('id')], $data);
    }


    /**
     * 填充用户数据
     * @param array $userData
     * @return int
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function dealtBreedUserData(array $userData): int
    {
        //'nickname','area','address', head_image
        $data = [];
        if (!empty($userData['area'])) {
            $data['area'] = $userData['area'];
        }

        if (!empty($userData['nickname'])) {
            $data['nickname'] = $userData['nickname'];
        }

        if (!empty($userData['address'])) {
            $data['address'] = $userData['address'];
        }

        if (!empty($userData['head_image'])) {
            $data['head_image'] = $userData['head_image'];
        }

        if (empty($data)) {
            return 0;
        }

        return BreederUserModel::updateSingle(['id' => adminBreederInfo('id')], $data);
    }

    /**
     * 我的仓库
     * @param int $limit
     * @param int $type
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getWarehouseData(int $limit = 15, int $type = 0, int $page = 0, int $show = 0): array
    {
        $where[] = ['user_id', '=', adminUserInfo('id')];
        $where[] = ['status', '=', 1];
        $where[] = ['deleted_at', '=', 0];

        if (!empty($type)) {
            $where[] = ['type', '=', $type];

        }

        return FormatBase::listData($this->handleResponse(WarehouseModel::getPage($where, $limit, '*, sum(buy_num) as buy_num_sum'), $page, $show, $limit));
    }

    /**
     * 我的服务(已使用)
     * @param int $limit
     * @param int $type
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getUseWarehouseData(int $limit = 15, int $type = 0): array
    {
        $where[] = ['user_id', '=', adminUserInfo('id')];

        if (!empty($type)) {
            $where[] = ['type', '=', $type];

        }

        return FormatBase::listData($this->handleResponse(WarehouseUseLogsModel::getPage($where, $limit, '*')));
    }

//    /**
//     * 我的好友列表
//     * @param int $limit
//     * @param string $nickname
//     * @param $mobile
//     * @return array
//     * @throws \Psr\Container\ContainerExceptionInterface
//     * @throws \Psr\Container\NotFoundExceptionInterface
//     */
//    public function myFriend(int $limit = 15, string $nickname = '', $mobile = ''): array
//    {
////        D(DB::table('farm_user_friend')->get());
//        $where[] = ['u.deleted_at', '=', 0];
//
//        if (!empty($nickname)) {
//            $where[] = ['u.nickname', 'like', '%' . $nickname . '%'];
//
//        }
//
//        if (!empty($mobile)) {
//            $where[] = ['u.mobile', 'like', '%' . $mobile . '%'];
//
//        }
//
//        $where[] = ['f.user_id', '=', adminUserInfo('id')];
//        $where[] = ['f.friend_status', '=', 2];
//        $where[] = ['f.deleted_at', '=', 0];
//
//        return FormatBase::listData($this->handleFriendResponse(UserModel::getPage($where, $limit, 'u.*')));
//    }

    /**
     * 排行榜展示
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function foodRank(): array
    {
        $where[] = ['deleted_at', '=', 0];
        return ($this->handleRankResponse(UserModel::getUserData($where, '', [], 10)));
    }



    /**
     * 用户详情
     * @param $mobile
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function searchFriend($mobile = ''): array
    {
        $where[] = ['deleted_at', '=', 0];

        if (!empty($mobile)) {
            $where[] = ['mobile', '=', $mobile];

        }

        return ($this->handleUserResponse(UserModel::getSingle($where)));
    }

    /**
     * 申请添加好友请求
     * @param int $userId
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function addFriend(int $userId = 0): bool
    {
        if (empty($userId)) {
            return false;
        }

        //查看好友是否给自己发过好友申请
        $info = UserFriendModel::getSingle([
            'user_id' => $userId,
            'user_friend_id' => adminUserInfo('id'),

        ], 'friend_status', [1]);

        $this->beginTransaction();
        try {
            if (!empty($info)) {
                //发过，1修改好友表状态
                UserFriendModel::updateSingle([
                    'user_id' => $userId,
                    'friend_status' => 1,
                    'user_friend_id' => adminUserInfo('id'),
                ], ['friend_status' => 2, 'updated_at' => time()]);

                //并 添加自己的好友表数据
                UserFriendModel::insertSingle([
                    'user_id' => adminUserInfo('id'),
                    'user_friend_id' => $userId,
                    'friend_status' => 2,
                    'created_at' => time(),
                    'updated_at' => time(),
                    'style' => 2,
                ]);

                //2修改好友消息状态
                UserMessageModel::updateSingle(['user_id' => adminUserInfo('id'), 'friend_user_id' => $userId, 'type' => 4], ['type' => 8]);

            } else {
                //没发过，查看自己是否给好友发过申请
                $infoTemp = UserFriendModel::getSingle([
                    'user_id' => adminUserInfo('id'),
                    'user_friend_id' => $userId,
                ], 'friend_status', [1, 2]);
                if (!empty($infoTemp)) {
                    //发过， 添加消息表
                    $this->addUserMessage($userId, adminUserInfo('id'), 4, 0, '', $infoTemp['id']);

                } else {
                    //没发过，1添加好友表
                    $infoTemp = UserFriendModel::insertSingle([
                        'user_id' => adminUserInfo('id'),
                        'user_friend_id' => $userId,
                        'friend_status' => 1,
                        'created_at' => time(),
                        'style' => 1,
                    ]);

                    //2添加好友消息
                    $this->addUserMessage($userId, adminUserInfo('id'), 4, 0, '', $infoTemp);

                }
            }

            $this->commit();

        } catch (Exception $e) {
            $this->rollBack();

            return false;
        }

        return true;
    }

    /**
     * 用户详情
     * @param array $data
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function handleUserResponse(array $data = []): array
    {
        $temp = [];
        //商品数
        $temp['id'] = $data['id'];
        $temp['head_img_url'] = $data['head_img_url'];
        $temp['nickname'] = $data['nickname'];
        $temp['mobile'] = desensitize($data['mobile'], 3, 4);

        //查询是否是好友
        $info = UserFriendModel::getSingle([
            'user_id' => adminUserInfo('id'),
            'user_friend_id' => $data['id'],

        ]);

        if (!empty($info)) {
            $temp['friend_status'] = $info['friend_status'];

        } else {
            $temp['friend_status'] = 0;

        }

        return $temp;
    }

    /**
     * 我的好友列表
     * @param array $data
     * @return array
     */
    public function handleFriendResponse(array $data = []): array
    {
        $list = [];
        foreach ($data['data'] as $value) {
            $temp = [];
            //商品数
            $temp['id'] = $value['id'];
            $temp['head_img_url'] = $value['head_img_url'];
            $temp['nickname'] = $value['nickname'];
            $temp['mobile'] = desensitize($value['mobile'], 3, 4);

            $list[] = $temp;
        }
        $data['data'] = $list;

        return $data;
    }

    /**
     * 我的好友列表
     * @param array $data
     * @return array
     */
    public function handleRankResponse(array $data = []): array
    {
        $list = [];
        foreach ($data as $key => $value) {
            $temp = [];
            //商品数
            $temp['id'] = $value['id'];
            $temp['rank_num'] = $key + 1;
            $temp['head_img_url'] = $value['head_img_url'];
            $temp['nickname'] = $value['nickname'];
            $temp['food_num'] = $value['food_num'];

            $list[] = $temp;
        }

        return $list;
    }

    /**
     * 我的好友列表
     * @param array $data
     * @return array
     */
    public function handleUserPayResponse(array $data = []): array
    {
        $list = [];
        foreach ($data['data'] as $value) {
            $temp = [];
            $temp['id'] = $value['id'];
            $temp['pay_time'] = !empty($value['pay_time']) ? date('Y-m-d H:i:s', $value['pay_time']) : '';

            if (date('Y-m-d', $value['pay_time']) == date('Y-m-d', time())) {
                $temp['pay_time_message'] = '今天';

            } else if (date('Y-m-d', $value['pay_time']) == date('Y-m-d', (time() - 86400))) {
                $temp['pay_time_message'] = '昨天';

            } else {
                $temp['pay_time_message'] = '';

            }
            $temp['pay_price'] = $value['pay_price'];
            $temp['name'] = $value['name'];
            $temp['style'] = $value['style'];
            $temp['buy_num'] = $value['buy_num'];

//            //宠物名称 一对一with写法
//            if (!empty($value['pets_name'][0]['pets_name'])){
//                $temp['pets_name'] = $value['pets_name'][0]['pets_name'];
//            }else{
//                $temp['pets_name'] = '';
//            }

            $list[] = $temp;
        }
        $data['data'] = $list;

        return $data;
    }

    public function handleUserBuy($pets, $goodsId): int
    {
        $num = 0;
        foreach ($pets as $value) {
            switch ($goodsId) {
                case 1:
                    if ($value['cat_id'] == 1) {
                        $num += $value['small_food'];
                    }
                    break;
                case 2:
                    if ($value['cat_id'] == 1) {
                        $num += $value['middle_food'];
                    }
                    break;
                case 3:
                    if ($value['cat_id'] == 1) {
                        $num += $value['big_food'];
                    }
                    break;

                case 4:
                    if ($value['cat_id'] == 2) {
                        $num += $value['small_food'];
                    }
                    break;
                case 5:
                    if ($value['cat_id'] == 2) {
                        $num += $value['middle_food'];
                    }
                    break;
                case 6:
                    if ($value['cat_id'] == 2) {
                        $num += $value['big_food'];
                    }
                    break;

                case 7:
                    if ($value['cat_id'] == 3) {
                        $num += $value['small_food'];
                    }
                    break;
                case 8:
                    if ($value['cat_id'] == 3) {
                        $num += $value['middle_food'];
                    }
                    break;
                case 9:
                    if ($value['cat_id'] == 3) {
                        $num += $value['big_food'];
                    }
                    break;

            }

        }

        return $num;
    }

    public function handleResponse(array $data = [], int $page = 0, int $show = 0, int $isL = 0): array
    {
        if (!empty($show) && (ceil($data['total'] / $isL) == $page)) {
            $GoodList = [];
            //查询1-9的基础套餐
            $rGoods = GoodsModel::getData([], 'id', [1, 2, 3, 4, 5, 6, 7, 8, 9]);
            $rPets = PetsModel::getData(['adopt_user_id' => adminUserInfo('id')]);
            foreach ($rGoods as $key => $value) {
                unset($rTemp);
                $rTemp['id'] = 99999;
                $rTemp['user_id'] = adminUserInfo('id');
                $rTemp['ord_id'] = 0;
                $rTemp['ordpro_id'] = 0;
                $rTemp['goods_id'] = $value['id'] ?? 0;
                $rTemp['goods_name'] = $value['goods_name'] ?? '默认套餐';
                $rTemp['status'] = 1;
                $rTemp['created_at'] = time();
                $rTemp['updated_at'] = 0;
                $rTemp['type'] = 2;
                $rTemp['weight'] = $value['weight'] ?? '';
                $rTemp['weight_type'] = $value['weight_type'] ?? '';
                $rTemp['weight_json'] = $value['weight_json'] ?? '';
                $rTemp['buy_num_sum'] = $this->handleUserBuy($rPets, $value['id'] ?? 0);
                $rTemp['goods_msg'][] = $value;
                $GoodList[] = $rTemp;
            }

            $data['data'] = array_merge($data['data'], $GoodList);
        }

        $list = [];
        foreach ($data['data'] as $value) {

            $temp = [];

            //buy_num_sum
            $temp['id'] = $value['id'];
            $temp['goods_id'] = $value['goods_id'];
            if (isset($value['buy_num_sum'])) {
                if ($value['buy_num_sum'] <= 0 && $value['id'] <> 99999) {
                    continue;
                }
                $temp['buy_num_sum'] = $value['buy_num_sum'];
            } else {
                $temp['buy_num_sum'] = 1;
            }

            //创建时间
            $temp['created_at'] = !empty($value['use_num']) ? date('Y-m-d H:i:s', time()) : '';

            //商品名称 一对一with写法
            if (!empty($value['goods_msg'][0]['goods_name'])) {
                $temp['goods_name'] = $value['goods_msg'][0]['goods_name'];
            } else {
                $temp['goods_name'] = '';
            }

            //商品图片 一对一with写法
            if (!empty($value['goods_msg'][0]['original_img'])) {
                $temp['original_img'] = $value['goods_msg'][0]['original_img'];
            } else {
                $temp['original_img'] = '';
            }

            //商品简介 一对一with写法
            if (!empty($value['goods_msg'][0]['goods_remark'])) {
                $temp['goods_remark'] = $value['goods_msg'][0]['goods_remark'];
            } else {
                $temp['goods_remark'] = '';
            }

            //商品类型 一对一with写法
            if (!empty($value['goods_msg'][0]['type'])) {
                $temp['type'] = $this->handleTypePets($value['goods_msg'][0]['type']);

            } else {
                $temp['type'] = '';
            }

            //商品适用宠物 一对一with写法
            if (!empty($value['goods_msg'][0]['fit_pets'])) {
                $temp['fit_pets'] = $this->handleFitsPets($value['goods_msg'][0]['fit_pets']);

            } else {
                $temp['fit_pets'] = '';
            }

            if ($value['type'] == 1 || $value['type'] == 3) {
                //商品、服务
                unset($tempSons);
                //商品名称 一对一with写法
                if (!empty($value['goods_msg'][0]['goods_name'])) {
                    $tempSons['goods_name'] = $value['goods_msg'][0]['goods_name'];
                } else {
                    $tempSons['goods_name'] = '';
                }

                //食物重量/服务时常 一对一with写法
                if (!empty($value['goods_msg'][0]['weight'])) {
                    $tempSons['weight'] = $value['goods_msg'][0]['weight'];
                } else {
                    $tempSons['weight'] = '';
                }

                //重量类型  1：g（克）  2：kg（千克） 3：h（小时） 一对一with写法
                if (!empty($value['goods_msg'][0]['weight_type'])) {
                    $tempSons['weight_type'] = $value['goods_msg'][0]['weight_type'];
                } else {
                    $tempSons['weight_type'] = '';
                }

                if (!empty($value['use_num'])) {
                    //商品数
                    $tempSons['num'] = $value['use_num'];
                } else {
                    $tempSons['num'] = 1;

                }

                $temp['goods_message'][] = $tempSons;
            } elseif ($value['type'] == 2) {
                //套餐
                unset($tempSons);

                //json数组
                if (!empty($value['goods_msg'][0]['weight_json'])) {
                    $tempSons = json_decode($value['goods_msg'][0]['weight_json'], true);
                } else {
                    $tempSons = '';
                }

                $temp['goods_message'] = $tempSons;

            } else {
                $temp['goods_message'] = [];

            }


            $list[] = $temp;
        }

        $data['data'] = $list;

        return $data;
    }

    /**
     * 修改用户昵称
     * @param string $name
     * @return int
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function userUpdate(string $name = ''): int
    {
        return UserModel::updateSingle(['id' => adminUserInfo('id')], ['nickname' => $name]);

    }

    /**
     * 同意好友请求
     * @param int $id
     * @param int $status 1同意 2拒绝
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function agreeJoinFriends(int $id = 0, int $status = 0): bool
    {
        //查询好友关系是否是 1等待
        $userOne = UserFriendModel::getSingle(['id' => $id, 'friend_status' => 1]);

        if (empty($userOne)) {
            //不是，返回false
            return false;
        }

        if (empty($status)) {
            return false;
        }

        //是，同意，生成一条数据 && 状态改2
        if ($status == 1) {
            $this->beginTransaction();
            try {
                UserFriendModel::insertSingle([
                    'user_id' => adminUserInfo('id'),
                    'user_friend_id' => $userOne['user_id'] ?? 0,
                    'friend_status' => 2,
                    'created_at' => time(),
                    'updated_at' => time(),
                    'style' => 2,
                ]);
                //状态改2
                UserFriendModel::updateSingle(['id' => $id, 'friend_status' => 1], ['friend_status' => 2, 'updated_at' => time()]);
                //修改消息表状态
                UserMessageModel::updateSingle(['user_id' => adminUserInfo('id'), 'friend_user_id' => $userOne['user_id'], 'type' => 4], ['type' => 8]);

                $this->commit();

            } catch (Exception $e) {
                $this->rollBack();

                return false;
            }
        }

        //是，不同意，状态改3
        if ($status == 2) {
            UserFriendModel::updateSingle(['id' => $id, 'friend_status' => 1], ['friend_status' => 3, 'updated_at' => time()]);

            //添加消息表通知
            UserMessageModel::updateSingle(['user_id' => adminUserInfo('id'), 'friend_user_id' => $userOne['user_id'], 'type' => 4], ['type' => 9]);

        }

        return true;
    }

    /**
     * 用户点击签到
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function clickLogin(): array
    {
        //判断今天是否登录
        $userOne = UserLoginLogsModel::getSingle(['created_at' => $today = strtotime(date("Y-m-d"), time()), 'user_id' => adminUserInfo('id')]);

        if (!empty($userOne)) {
            return [1009, '今天已经签到过了'];
        }

        //登录，farm_user_login_logs加数据 ，farm_user.login_day+1
        $this->beginTransaction();
        try {
            UserLoginLogsModel::insertSingle([
                'user_id' => adminUserInfo('id'),
                'created_at' => $today = strtotime(date("Y-m-d"), time())
            ]);

            UserModel::addIncrement(
                ['id' => adminUserInfo('id')],
                'login_day'
            );

            //查询现在用户登录天数
            $userDay = UserModel::getSingle(['id' => adminUserInfo('id')]);

            //发放奖励
            $this->handleAward(adminUserInfo('id'), $userDay['login_day'] ?? 1);

            $this->commit();

        } catch (Exception $e) {
            $this->rollBack();
            return [1010, '参数错误'];
        }

        return [];
    }

    /**
     * 添加用户消息
     * @param int $userId
     * @param int $friendUserId
     * @param int $type
     * @param int $petsId
     * @return int
     */
    public function addUserMessage(int $userId = 0, int $friendUserId = 0, int $type = 1, int $petsId = 0, string $content = '', int $logic = 0): int
    {
        //宠物信息
        $petsOne = PetsModel::getSingle(['id' => $petsId]);

        if (empty($userId) && !empty($petsOne)) {
            $userId = $petsOne['adopt_user_id'];
        }

        //用户信息
        $userOne = UserModel::getSingle(['id' => $userId]);
        $friendUserOne = UserModel::getSingle(['id' => $friendUserId]);

        $temp = [];

        $temp['type'] = $type;
        $temp['user_id'] = $userId;
        $temp['friend_user_id'] = $friendUserId;
        $temp['status'] = 1;

        //获取content
        switch ($type) {
            //类型 1好友投喂 2领养成功 3喂养食物不足 4好友申请 5屠宰提醒 6配送提醒 7系统消息 8好友申请（已同意） 9好友申请（已拒绝）
            case 1:
                $content = enum_user_message::USER_FOOD;;
                $content = str_replace("USER", $friendUserOne['nickname'], $content);
                $content = str_replace("PETS", $petsOne['pets_name'], $content);
                break;
            case 2:
                $content = enum_user_message::ADOPT_SUCCESS;;
                $content = str_replace("PETS", $petsOne['pets_name'], $content);
                break;
            case 3:
                $content = enum_user_message::NONE_FOOD;;
                break;
            case 4:
                $content = enum_user_message::FRIEND_REQUEST;;
                $content = str_replace("USER", $friendUserOne['nickname'], $content);
                $content = str_replace("PHONE", !empty($friendUserOne['mobile']) ? '（' . $friendUserOne['mobile'] . '）申请' : '申请', $content);
                $temp['logic'] = $logic;

                break;
            case 5:
                $content = enum_user_message::SLAUGHTER_MESSAGE;;
                break;
            case 6:

                break;
        }

        $temp['content'] = $content;
        $temp['created_at'] = time();

        return UserMessageModel::insertSingle($temp);

    }

    public function sendMessage()
    {

    }

    /**
     * @param $params
     * @return string
     */
    public function handleFitsPets($params): string
    {
        $temp = [];
        foreach (explode(',', $params) as $vs) {
            switch ($vs) {
                case 1:
                    $temp['fit_pets'][] = '猪';

                    break;
                case 2:
                    $temp['fit_pets'][] = '羊';

                    break;
                case 3:
                    $temp['fit_pets'][] = '鸡';

                    break;
                default:
                    break;
            }
        }
        return implode(',', $temp['fit_pets']);
    }

    public function handleTypePets($params): string
    {
        $temp = '';
        switch ($params) {
            case 1:
                $temp = '食物';

                break;
            case 2:
                $temp = '套餐';

                break;
            case 3:
                $temp = '服务';

                break;
            default:
                break;
        }

        return $temp;
    }

    /**
     * 获取用户信息
     * @param array $sysUserOne
     * @return array
     */
    public function getUserInfo(array $sysUserOne = []): array
    {
        //获取角色
        $roleAll = SysUserRoleModel::getDataOne(['uid' => $sysUserOne['id']]);

        //获取当前角色的有权限的菜单
        $menuList = SysRolePermissionsModel::userRoleAll('rp.role_id', array_column($roleAll, 'role_id'));
        //处理菜单，按钮等数据
        //菜单
        $menuInfo = [];

        //按钮权限集合
        $buttonInfo = [];

        foreach ($menuList as $value) {
            $value['meta']['title'] = $value['title'];
            $value['meta']['icon'] = $value['icon'];

            unset($value['title'], $value['icon']);

            if ($value['type'] == 2) {
                $buttonInfo[] = $value;
            }
            if ($value['type'] == 1) {
                $menuInfo[] = $value;
            }
        }

        foreach ($menuInfo as &$menu) {
            $menu['auth'] = [];
            foreach ($buttonInfo as $button) {
                if ($button['parent_id'] == $menu['id']) {
                    $menu['auth'][] = $button;
                }
            }
        }

        $menuInfo = makeTree($menuInfo, 'id', 'parent_id', 'children');
        $userAuth = array_column($menuList, 'tag');

        return [
            'id' => $sysUserOne['id'],
            'account' => $sysUserOne['account'],
            'nickname' => $sysUserOne['nickname'],
            'email' => $sysUserOne['email'],
            'mobile' => $sysUserOne['mobile'],
            'menuInfo' => $menuInfo,
            'userAuth' => $userAuth,
            'clearInfo' => [],
        ];
    }

    public function handleorder($params){

        //获取消息列表
        $where_temp['user_id'] = adminUserInfo('id');
        if (!empty($params['published'])){
            $where_temp['status'] = 5;
        }

        $userList = OrderModel::getPage($where_temp, $params['limit'] ?? 15);

        //获取所有的tag
        $tags = TagsModel::getUserData(['parent_id'=> 0]);
        $tags = array_column($tags, null, 'id');

        $list = [];
        foreach ($userList['data'] as $value){
            unset($temp);
            $temp['id'] = $value['id'] ?? '';
            $temp['public_id'] = $value['public_id'] ?? '';
            $temp['status'] = $value['status'] ?? '';
            $temp['created_at'] = $value['created_at'] ?? '';
            $temp['style'] = $value['style'] ?? '';
            $temp['money'] = $value['money'] ?? '';
            $temp['task_id'] = $value['task_id'] ?? '';
            $temp['no'] = '';
            $temp['rpc_id'] = '';
            $temp['create_lxr_name'] = '';
            $temp['create_lxr_mobile'] = '';
            $temp['create_title'] = '';
            $temp['plain_end_time'] = '';

            if (!empty($value['user_public'][0]['no'])){
                $temp['no'] = $value['user_public'][0]['no'];
            }

            if (!empty($value['user_public'][0]['rpc_id'])){
                $temp['rpc_id'] = $value['user_public'][0]['rpc_id'];
            }

            if (!empty($value['user_public'][0]['create_lxr_name'])){
                $temp['create_lxr_name'] = $value['user_public'][0]['create_lxr_name'];
            }

            if (!empty($value['user_public'][0]['create_lxr_mobile'])){
                $temp['create_lxr_mobile'] = $value['user_public'][0]['create_lxr_mobile'];
            }

            if (!empty($value['user_public'][0]['create_title'])){
                $temp['create_title'] = $value['user_public'][0]['create_title'];
            }

            if (!empty($value['user_public'][0]['plain_end_time'])){
                $temp['plain_end_time'] =  date('Y-m-d H:i:s', $value['user_public'][0]['plain_end_time']);
            }

            //信息类型 1普通信息 2vip信息
            $temp['style_task'] = '';
            if (!empty($value['user_public'][0]['style_task'])){
                $temp['style_task'] = $value['user_public'][0]['style_task'];
            }
            //一级分类
            $temp['cat_1_msg'] = '';
            if (!empty($value['user_public'][0]['cat_1'])){
                $temp['cat_1_msg'] = $tags[$value['user_public'][0]['cat_1']]['name'];
            }
            //发布地区
            $temp['area_json'] = '';
            if (!empty($value['user_public'][0]['area_json'])){
                $temp['area_json'] = json_decode($value['user_public'][0]['area_json'], true);
                $citu_ids = [];
                if (!empty($temp['area_json']) && is_array($temp['area_json'])){
                    foreach ($temp['area_json'] as $vs_1){
                        foreach ($vs_1 as $vs_2){
                            $citu_ids[] = $vs_2;
                        }
                    }

                    $city_all = CityChinaModel::getUserData([], 'code', $citu_ids);
                    $city_all = array_column($city_all, null,'code');

                    foreach ($temp['area_json'] as $vs_1){
                        $temp_city = [];
                        foreach ($vs_1 as $vs_2){
                            if (!empty($city_all[$vs_2]['name'])){
                                $temp_city[] = $city_all[$vs_2]['name'];
                            }
                        }
                        $temp['area_json_msg'][] = $temp_city;
                    }
                }else{
                    $temp['area_json_msg'] = [];
                }

            }
            //标签
            $temp['tag_json'] = '';
            if (!empty($value['user_public'][0]['tag_json'])){
                $temp['tag_json'] = json_decode($value['user_public'][0]['tag_json'], true);
            }
            //贡献样式几 样式类型 1样式1  2样式2
            $temp['share_style'] = '';
            if (!empty($value['user_public'][0]['share_style'])){
                $temp['share_style'] = $value['user_public'][0]['share_style'];
            }

            //是否贡献 1是 2否
            $temp['is_share'] = '';
            if (!empty($value['user_public'][0]['is_share'])){
                $temp['is_share'] = $value['user_public'][0]['is_share'];
            }

            $list[] = $temp;
        }
        $userList['data'] = $list;

        return $userList;
    }

    public function handleOrderLogs($params)
    {
        if (!empty($params['cat_1'])){
            $where['up.cat_1'] = $params['cat_1'];
        }

        if (!empty($params['task_id'])){
            $where['info_op_logs.task_id'] = $params['task_id'];
        }

        if (!empty($params['style']) && !is_array($params['style'])){
            $where['up.style'] = $params['style'];
        }

        if (!empty($params['no'])){
            $where[] = ['up.no', 'like', '%' . $params['no'] . '%'];
        }

        $where['up.user_id'] = adminUserInfo('id');

        $key_style = '';
        $value_style = [];
        if(!empty($params['style_type'])){
            if(is_array($params['style_type'])){
                $key_style = 'info_op_logs.style';
                $value_style = $params['style_type'];
            }
        }

        $userList = OpLogsModel::getPage($where, $params['limit'] ?? 15, '*, info_op_logs.content as log_content', $key_style, $value_style);

        $list = [];
        foreach ($userList['data'] as $value){
            unset($temp);
            $temp['id'] = $value['id'] ?? '';
            $temp['cat_1_id'] = '';
            $temp['cat_2_id'] = '';
            $temp['style'] = $value['style'] ?? '';
            $temp['msg'] = $value['msg'] ?? '';
            $temp['created_at'] = $value['created_at'] ?? '';
            $temp['op_user_id'] = $value['op_user_id'] ?? '';
            $temp['task_id'] = $value['public_id'] ?? '';
            $temp['no'] = $value['no'] ?? '';
            $temp['rpc_id'] = $value['rpc_id'] ?? '';
            $temp['pay_sum'] = $value['pay_sum'] ?? '';
            $temp['op_user_id_msg'] = '';
            $temp['create_lxr_name'] = $value['create_lxr_name'] ?? '';
            $temp['create_lxr_mobile'] = $value['create_lxr_mobile'] ?? '';
            $temp['create_title'] = $value['create_title'] ?? '';
            $temp['plain_end_time'] = date('Y-m-d H:i:s', $value['plain_end_time']) ?? '';
            $temp['log_content'] = [];

            if (!empty($value['log_content'])){
                $temp_log_content = json_decode($value['log_content'], true);
                $temp_user = UserPublicModel::getUserData([], 'id', $temp_log_content, 5, 'id, user_id, rpc_id');
                foreach ($temp_user as &$user_val){
                    $user_val['user_id'] = '';
                    $user_val['mobile'] = '';
                    $user_val['nickname'] = '';
                    $user_val['user_image_url'] = '';
                    if (!empty($user_val['users'][0]['id'])){
                        $user_val['user_id'] = $user_val['users'][0]['id'];
                    }

                    if (!empty($user_val['users'][0]['mobile'])){
                        $user_val['mobile'] = $user_val['users'][0]['mobile'];
                    }

                    if (!empty($user_val['users'][0]['nickname'])){
                        $user_val['nickname'] = $user_val['users'][0]['nickname'];
                    }

                    if (!empty($user_val['users'][0]['head_img_url'])){
                        $user_val['user_image_url'] = $user_val['users'][0]['head_img_url'];
                    }

                    unset($user_val['users']);
                }
                $temp['log_content'] = $temp_user;
            }

            if (!empty($value['sys_users'][0]['nickname'])){
                $temp['op_user_id_msg'] = $value['sys_users'][0]['nickname'];
            }

            if (!empty($value['cat_1'][0]['name'])){
                $temp['cat_1_msg'] = $value['cat_1'][0]['name'];
            }

            if (!empty($value['cat_2'][0]['name'])){
                $temp['cat_2_msg'] = $value['cat_2'][0]['name'];
            }

            if (!empty($value['cat_1'][0]['id'])){
                $temp['cat_1_id'] = $value['cat_1'][0]['id'];
            }

            if (!empty($value['cat_2'][0]['id'])){
                $temp['cat_2_id'] = $value['cat_2'][0]['id'];
            }
            $list[] = $temp;
        }
        $userList['data'] = $list;

        return $userList;
    }

    public function handleOrderLogsSearch($params)
    {
        if (!empty($params['cat_1'])){
            $where['up.cat_1'] = $params['cat_1'];
        }

        if (!empty($params['task_id'])){
            $where['info_op_logs_search.task_id'] = $params['task_id'];
        }

        if (!empty($params['style']) && !is_array($params['style'])){
            $where['up.style'] = $params['style'];
        }

        if (!empty($params['no'])){
            $where[] = ['up.no', 'like', '%' . $params['no'] . '%'];
        }

        $where['up.user_id'] = adminUserInfo('id');

        $key_style = '';
        $value_style = [];
        if(!empty($params['style_type'])){
            if(is_array($params['style_type'])){
                $key_style = 'info_op_logs_search.style';
                $value_style = $params['style_type'];
            }
        }

        $userList = OpLogsSearchModel::getPage($where, $params['limit'] ?? 15, '*, info_op_logs_search.content as log_content', $key_style, $value_style);

        $list = [];
        foreach ($userList['data'] as $value){
            unset($temp);
            $temp['id'] = $value['id'] ?? '';
            $temp['cat_1_id'] = '';
            $temp['cat_2_id'] = '';
            $temp['style'] = $value['style'] ?? '';
            $temp['msg'] = $value['msg'] ?? '';
            $temp['created_at'] = $value['created_at'] ?? '';
            $temp['op_user_id'] = $value['op_user_id'] ?? '';
            $temp['task_id'] = $value['public_id'] ?? '';
            $temp['no'] = $value['no'] ?? '';
            $temp['rpc_id'] = $value['rpc_id'] ?? '';
            $temp['pay_sum'] = $value['pay_sum'] ?? '';
            $temp['op_user_id_msg'] = '';
            $temp['create_lxr_name'] = $value['create_lxr_name'] ?? '';
            $temp['create_lxr_mobile'] = $value['create_lxr_mobile'] ?? '';
            $temp['create_title'] = $value['create_title'] ?? '';
            $temp['plain_end_time'] = date('Y-m-d H:i:s', $value['plain_end_time']) ?? '';
            $temp['log_content'] = [];

            if (!empty($value['log_content'])){
                $temp_log_content = json_decode($value['log_content'], true);
                $temp_user = UserPublicSearchModel::getUserData([], 'id', $temp_log_content, 5, 'id, user_id, rpc_id');
                foreach ($temp_user as &$user_val){
                    $user_val['user_id'] = '';
                    $user_val['mobile'] = '';
                    $user_val['nickname'] = '';
                    $user_val['user_image_url'] = '';
                    if (!empty($user_val['users'][0]['id'])){
                        $user_val['user_id'] = $user_val['users'][0]['id'];
                    }

                    if (!empty($user_val['users'][0]['mobile'])){
                        $user_val['mobile'] = $user_val['users'][0]['mobile'];
                    }

                    if (!empty($user_val['users'][0]['nickname'])){
                        $user_val['nickname'] = $user_val['users'][0]['nickname'];
                    }

                    if (!empty($user_val['users'][0]['head_img_url'])){
                        $user_val['user_image_url'] = $user_val['users'][0]['head_img_url'];
                    }

                    unset($user_val['users']);
                }
                $temp['log_content'] = $temp_user;
            }

            if (!empty($value['sys_users'][0]['nickname'])){
                $temp['op_user_id_msg'] = $value['sys_users'][0]['nickname'];
            }

            if (!empty($value['cat_1'][0]['name'])){
                $temp['cat_1_msg'] = $value['cat_1'][0]['name'];
            }

            if (!empty($value['cat_2'][0]['name'])){
                $temp['cat_2_msg'] = $value['cat_2'][0]['name'];
            }

            if (!empty($value['cat_1'][0]['id'])){
                $temp['cat_1_id'] = $value['cat_1'][0]['id'];
            }

            if (!empty($value['cat_2'][0]['id'])){
                $temp['cat_2_id'] = $value['cat_2'][0]['id'];
            }
            $list[] = $temp;
        }
        $userList['data'] = $list;

        return $userList;
    }


}
